/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.*;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.security.util.JWTUtil;
import com.jeeplus.modules.sys.service.RoleService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import sun.misc.BASE64Encoder;

/**
 * 用户Controller
 *
 * @author jeeplus
 * @version 2016-8-29
 */
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    //二维码地址
    @Value("${qrUrl}")
    private String qrUrl;
    //二维码失效时间
    @Value("${loseTime}")
    private int loseTime;
    //接口AppKeyValue
    @Value("${AppKeyValue}")
    private String AppKeyValue;
    //私钥
    @Value("${GX_PUBLIC_KEY}")
    private String GX_PUBLIC_KEY;
    public static final String VERIFICATION_CODE_CACHE = "verificationCodeCache";
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return userService.get(id);
        } else {
            return new User();
        }
    }

//    @RequiresPermissions(value = {"sys:user:view", "sys:user:add", "sys:user:edit"}, logical = Logical.OR)
    @GetMapping("queryById")
    public AjaxJson queryById(User user) {
        return AjaxJson.success().put("user", user);
    }

    @RequiresPermissions("sys:user:list")
    @GetMapping("list")
    public AjaxJson list(String pageNo, String pageSize,String orderBy ,String loginName,String name) {
        Map<String,Object> map = new HashedMap();
        PageBean<User> page = userService.getUserList(pageNo,pageSize,orderBy,loginName,name);
        map.put("list",page.getDatas());
        map.put("count",page.getTotalNum());
        return AjaxJson.success().put("page", map);
    }

    @RequiresPermissions(value = {"sys:user:add", "sys:user:edit"}, logical = Logical.OR)
    @PostMapping("save")
    public AjaxJson save(User user) {
        String regex=".*[a-zA-Z]+.*";
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher mts = Pattern.compile(regEx).matcher(user.getNewPassword());
        Matcher m = Pattern.compile(regex).matcher(user.getNewPassword());
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("不允许操作!");
        }
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            if(user.getNewPassword().length()>=8 && mts.find() && m.find()){
                user.setPassword(userService.entryptPassword(user.getNewPassword()));
            }else{
                return AjaxJson.error("用户密码强度不够！");
            }
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(user);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        if (!isCheckLoginName(user.getOldLoginName(), user.getLoginName())) {
            return AjaxJson.error("保存用户'" + user.getLoginName() + "'失败，登录名已存在!");
        }
        // 角色数据有效性验证，过滤不在授权内的角色
        List<Role> roleList = Lists.newArrayList();
        List<String> roleIdList = user.getRoleIdList();
        for (String roleId : roleIdList) {
            roleList.add(roleService.get(roleId));
        }
        user.setRoleList(roleList);

        // 保存用户信息
        userService.saveUser(user);
        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
            UserUtils.clearCache();
        }
        return AjaxJson.success("保存用户'" + user.getLoginName() + "'成功!");

    }

    /**
     * 批量删除用户
     */
    //@ApiOperation(value = "删除用户")
    @RequiresPermissions("sys:user:del")
    @DeleteMapping("delete")
    public AjaxJson delete(String ids) {
        String idArray[] = ids.split(",");
        AjaxJson j = new AjaxJson();
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作!");
        }
        StringBuffer msg = new StringBuffer();
        boolean success = true;
        for (String id : idArray) {
            User user = userService.get(id);
            if (UserUtils.getUser().getId().equals(user.getId())) {
                success = false;
                msg.append("["+user.getLoginName()+"]删除失败，不允许删除当前用户!<br/>");
            } else if (User.isAdmin(user.getId())) {
                success = false;
                msg.append("["+user.getLoginName()+"]删除失败，不允许删除超级管理员!<br/>");//删除用户失败, 不允许删除超级管理员用户
            } else {
                msg.append("["+user.getLoginName()+"]删除成功!<br/>");
                userService.deleteUser(user);//删除用户成功
            }
        }
        if(success){
            return AjaxJson.success(msg.toString());
        }else {
            return AjaxJson.error(msg.toString());
        }
    }

    /**
     * 导出用户数据
     *
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("sys:user:export")
    @GetMapping("export")
    public void exportFile(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        Page<User> page = userService.findPage(new Page<User>(request, response, -1), user);
        new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose();
    }

    /**
     * 导入用户数据
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:import")
    @PostMapping("import")
    public AjaxJson importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            for (User user : list) {
                try {
                    if (isCheckLoginName("", user.getLoginName())) {
                        user.setPassword(userService.entryptPassword("123456"));
                        BeanValidators.validateWithException(validator, user);
                        userService.saveUser(user);
                        successNum++;
                    } else {
                        failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
                        failureNum++;
                    }
                } catch (ConstraintViolationException ex) {
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    failureNum++;
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            return AjaxJson.success("已成功导入 " + successNum + " 条用户" + failureMsg);
        } catch (Exception e) {
            return AjaxJson.error("导入用户失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @return
     */
    @RequiresPermissions("sys:user:import")
    @GetMapping("import/template")
    public AjaxJson importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "用户数据导入模板.xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            return AjaxJson.error("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }



    private boolean isCheckLoginName(String oldLoginName, String loginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
           return true;
        } else if (loginName != null && userService.getUserByLoginName(loginName) == null) {
            return true;
        }
      return false;
    }


    /**
     * 用户信息显示编辑保存
     *
     * @param user
     * @return
     */
    @RequiresPermissions("user")
    @PostMapping("saveInfo")
    public AjaxJson infoEdit(User user) {
        User currentUser = UserUtils.getUser();
        if (jeePlusProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        if (user.getName() != null)
            currentUser.setName(user.getName());
        if (user.getEmail() != null)
            currentUser.setEmail(user.getEmail());
        if (user.getPhone() != null)
            currentUser.setPhone(user.getPhone());
        if (user.getMobile() != null)
            currentUser.setMobile(user.getMobile());
        if (user.getRemarks() != null)
            currentUser.setRemarks(user.getRemarks());
        if (user.getSign() != null)
            currentUser.setSign(user.getSign());
        userService.updateUserInfo(currentUser);
        return AjaxJson.success("修改个人资料成功!");
    }


    /**
     * 用户头像显示编辑保存
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequiresPermissions("user")
    @PostMapping("imageUpload")
    public AjaxJson imageUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IllegalStateException, IOException {
        User currentUser = UserUtils.getUser();
        // 判断文件是否为空
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            if(StringUtils.isBlank(fileName)){
                response.setStatus(400);
                return AjaxJson.error("文件为空！").put("code",400);
            }else{
                fileName = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
                if(fileName.equals("png") || fileName.equals("jpg") || fileName.equals("bmp") || fileName.equals("jpeg")){
                    // 文件保存路径
                    String realPath = FileKit.getAttachmentDir() + "sys/user/images/";
                    // 转存文件
                    FileUtils.createDirectory(realPath);
                    file.transferTo(new File(realPath + file.getOriginalFilename()));
                    currentUser.setPhoto(FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename());
                    userService.updateUserInfo(currentUser);
                    return AjaxJson.success("上传成功!").put("path", FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename());
                }else{
                    response.setStatus(400);
                }
            }
        }
        return AjaxJson.error("文件错误！").put("code",400);
    }

    /**
     * 返回用户信息
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("info")
    public AjaxJson infoData() {
        return AjaxJson.success("获取个人信息成功!").put("role", UserUtils.getRoleList()).put("user", UserUtils.getUser());
    }



    /**
     * 返回用户信息
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("toThingCode")
    public AjaxJson toThingCode(String code,int isYYYZ) {
        if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int result = userService.toThingCode(code,UserUtils.getUser().getLoginName(),sdf.format(new Date()),isYYYZ);
            if(result >= 1){
                return AjaxJson.success("操作成功!");
            }else{
                return AjaxJson.error("insert error code:"+code);
            }
        }else{
            return AjaxJson.error("get user error");
        }
    }

    /**
     * 返回用户信息
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("getUser")
    public AjaxJson getUser() throws ParseException {
        Map<String,String> map = new HashMap<>(4);
        String tell;
        if(null != UserUtils.getUser()){
            //获取实时数据
            User user = userService.findUser(UserUtils.getUser().getLoginName());
            map.put("address",user.getAddress());
            map.put("name",user.getName());
            map.put("photo",user.getPhoto());
            map.put("id",UserUtils.getUser().getId());
            map.put("openid",UserUtils.getUser().getLoginName());
            tell = user.getPhone();
            if(tell.length() == 11){
                map.put("tell",tell.substring(0,3)+"*****"+tell.substring(tell.length()-3,tell.length()));
            }else{
                map.put("tell","");
            }
        }
        Boolean isFR = userService.checklegalUserCount(UserUtils.getUser().getLoginName());
        HashMap <String, Object> maps = userService.checklegalUser(UserUtils.getUser().getLoginName());
        if(maps != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //设置时间格式
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(sdf.parse(maps.get("startTime").toString()));//把当前时间赋给日历
            if(isFR){
                calendar.add(Calendar.YEAR, 1);  //后一年
                Date times = calendar.getTime();   //得到后一天的时间
                maps.put("endTime",sdf.format(times));
            }else{
                calendar.add(Calendar.DAY_OF_MONTH, 1);  //设置为后一天
                Date times = calendar.getTime();   //得到后一天的时间
                maps.put("endTime",sdf.format(times));
            }
        }

        return AjaxJson.success("获取个人信息成功!").put("user", map).put("checklegal",maps).put("isFR",isFR);
    }


    /**
     * 获取用户认证数据
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("getCheckUserValue")
    public AjaxJson getCheckUserValue() {
        MobileUserQR user = userService.getUserIdcard(UserUtils.getUser().getLoginName());
        return AjaxJson.success("获取个人信息成功!").put("name", user.getName()).put("tell",user.getTell());
    }



    /**
     * 返回用户信息 对接卓繁一业一证
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("getUserByToken")
    public AjaxJson getUserByToken(@RequestHeader("AppKey") String AppKey) {
        if (!AppKeyValue.equals(AppKey)) return AjaxJson.error("AppKey is error!").put("code", 400);
        if(null != UserUtils.getUser()){
            //获取实时数据
            try{
                return AjaxJson.success("获取个人信息成功!").put("user", EncryptUtils.aesEncrypt(JSONObject.fromObject(userService.getUserByToken(UserUtils.getUser().getLoginName())).toString(), GX_PUBLIC_KEY));
            }catch (Exception e){
                e.printStackTrace();
                return  AjaxJson.error("无效数据！");
            }

        }else {
            return AjaxJson.error("请先登录！");
        }
    }

//    /**
//     * 生成二维码
//     *
//     * @throws Exception
//     */
//    @GetMapping("createUserCode")
//    @RequiresPermissions("user")
//    public AjaxJson createUserCode() {
//        String realPath = FileKit.getAttachmentDir() + "qrcode/";
//        FileUtils.createDirectory(realPath);
//        String uuid = UUID.randomUUID().toString();
//        try {
//            if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                userService.insertQR(uuid,sdf.format(new Date()),loseTime,UserUtils.getUser().getLoginName());
//                String name = UserUtils.getUser().getLoginName()+".png"; //encoderImgId此处二维码的图片名
//                String filePath = realPath + name;  //存放路径
//                TwoDimensionCode.encoderQRCode(qrUrl + uuid, filePath, "png");//执行生成二维码
//                return AjaxJson.success("二维码生成成功").put("filePath", FileKit.getAttachmentUrl() + "qrcode/" + name);
//            }else{
//                log.error("用户未登录！");
//                return AjaxJson.error("用户未登录！");
//            }
//        } catch (Exception e) {
//            log.error("二维码生成失败:"+e.getMessage());
//            return AjaxJson.error("二维码生成失败");
//        }
//    }

    /**
     * 生成二维码
     *
     * @throws Exception
     */
    @GetMapping("createUserCode")
    @RequiresPermissions("user")
    public AjaxJson createUserCode() {
            synchronized(this) {
                SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSS");
                String uuid = sd.format(new Date());
                if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
                    userService.insertQR(uuid,DateUtils.getDateTime(),loseTime,UserUtils.getUser().getLoginName(),null);
                    return AjaxJson.success("二维码生成成功").put("path", qrUrl + uuid).put("loseTime",loseTime);
                }else{
                    log.error("用户未登录！");
                    return AjaxJson.error("用户未登录！");
                }
            }
    }

    /**
     * 获取用户uuid
     *
     * @throws Exception
     */
    @GetMapping("getUserCode")
    @RequiresPermissions("user")
    public AjaxJson getUserCode() {
        synchronized(this) {
            SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String uuid = sd.format(new Date());
            if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
                userService.insertQR(uuid,DateUtils.getDateTime(),loseTime,UserUtils.getUser().getLoginName(),null);
                return AjaxJson.success("二维码生成成功").put("uuid", uuid);
            }else{
                log.error("用户未登录！");
                return AjaxJson.error("用户未登录！");
            }
        }
    }

    /**
     * 生成二维码
     *
     * @throws Exception
     */
    @GetMapping("createUserQR")
    @RequiresPermissions("user")
    public AjaxJson createUserQR() {
        try {
            if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
                String uuid = UUID.randomUUID().toString();
                String key = Keys.getKeyValue(16);
                userService.insertQR(uuid,DateUtils.getDateTime(),loseTime,UserUtils.getUser().getLoginName(),key);
                Map<String, Object> userValue = userService.getUserValue(UserUtils.getUser().getLoginName());
                return AjaxJson.success().put("data",EncryptUtils.aesEncrypt(JSONObject.fromObject(userValue).toString(), key)).put("kid",uuid);
            }else{
                log.error("用户未登录！");
                return AjaxJson.error("用户未登录！");
            }
        } catch (Exception e) {
            log.error("二维码生成失败:"+e.getMessage());
            return AjaxJson.error("二维码生成失败");
        }
    }


    @RequiresPermissions("user")
    @PostMapping("savePwd")
    public AjaxJson savePwd(String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        String regex=".*[a-zA-Z]+.*";
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher mts = Pattern.compile(regEx).matcher(newPassword);
        Matcher m = Pattern.compile(regex).matcher(newPassword);
        if(newPassword.length()>=8 && mts.find() && m.find()){
            if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
                if (jeePlusProperites.isDemoMode()) {
                    return AjaxJson.error("演示模式，不允许操作！");
                }
                if (UserService.validatePassword(oldPassword, user.getPassword())) {
                    userService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                    return AjaxJson.success("修改密码成功！");
                } else {
                    return AjaxJson.error("修改密码失败，旧密码错误！");
                }
            }
            return AjaxJson.error("参数错误！");
        }else{
            return AjaxJson.error("密码参数不够！");
        }

    }


    /**
     * 保存签名
     */
    @PostMapping("saveSign")
    public AjaxJson saveSign(User user, boolean __ajax, HttpServletResponse response, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        User currentUser = UserUtils.getUser();
        currentUser.setSign(user.getSign());
        userService.updateUserInfo(currentUser);
        return AjaxJson.success("设置签名成功!");
    }

    @RequiresPermissions("user")
    @GetMapping("treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = userService.findUserByOfficeId(officeId);
        for (int i = 0; i < list.size(); i++) {
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_" + e.getId());
            map.put("pId", officeId);
            map.put("name", StringUtils.replace(e.getName(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }


    /**
     * web端ajax验证手机号是否可以注册（数据库中不存在）
     */
    //@ApiOperation("验证手机号")
    @GetMapping("validateMobile")
    public AjaxJson validateMobile(String mobile, HttpServletResponse response, Model model) {
        User user = userService.findUniqueByProperty("mobile", mobile);
        if (user == null) {
            return AjaxJson.success().put("noExist", true);
        } else {
            return AjaxJson.success().put("noExist", false);
        }
    }



    //@ApiOperation(value = "用户权限")
    @RequiresPermissions("user")
    @GetMapping("getPermissions")
    public Set<String> getPermissions() {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String token = UserUtils.getToken();
        String loginName = JWTUtil.getLoginName(token);
        User user = UserUtils.getByLoginName(loginName);
        if (user != null) {

            List<Menu> list = UserUtils.getMenuList();
            for (Menu menu : list) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(menu.getPermission())) {
                    // 添加基于Permission的权限信息
                    for (String permission : org.apache.commons.lang3.StringUtils.split(menu.getPermission(), ",")) {
                        info.addStringPermission(permission);
                    }
                }
            }
            // 添加用户权限
            info.addStringPermission("user");
            // 添加用户角色信息
            for (Role role : user.getRoleList()) {
                info.addRole(role.getEnname());
            }
        }
        return info.getStringPermissions();
    }


    @GetMapping("getMenus")
    @RequiresPermissions("user")
    public AjaxJson getMenus() {
        AjaxJson j = new AjaxJson();
        j.put("dictList", this.getDicts());
        j.put("permissions", this.getPermissions());
        j.put("menuList", MenuUtils.getMenus());
        j.put("routerList", RouterUtils.getRoutersByMenu());
        return j;
    }

    /**
     * 获取用户信息二维码链接
     * loseTime二维码链接失效时间
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "/getGxUserCode", method = RequestMethod.GET)
    public AjaxJson getGxUserCode(String uuid) {
        if(StringUtils.isNotBlank(uuid) && uuid.lastIndexOf("/") >= 0){
            uuid = uuid.substring(uuid.lastIndexOf("/")+1,uuid.length());
        }
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(uuid);
        if(m.find()) {
            return AjaxJson.error("暂无此数据！");
        }
        MobileGxUser mu = userService.getGxUserCode(uuid);
        if(null == mu){
            return AjaxJson.error("暂无此数据！");
        }else{
            userService.intoUserQR(mu.getName(),mu.getIdcard(),mu.getTell());
            mu.setBirthday(mu.getIdcard().substring(6,10));
            int sex = Integer.parseInt(mu.getIdcard().substring(16,17));
            if (sex % 2 == 0) {
                mu.setSex("女");
            } else {
                mu.setSex("男");
            }
            mu.setList(userService.findUserMaterial(mu.getIdcard()));
            return AjaxJson.success().put("data",mu).put("company",userService.findCompany(mu.getLoginName()));
        }
    }

    private Map<String, List<DictValue>> getDicts() {
        return DictUtils.getDictMap();
    }


    /**
     * 注销用户
     *
     * @throws Exception
     */
    @GetMapping("delUserValue")
    @RequiresPermissions("user")
    public AjaxJson delUserValue() {
        if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
            if(userService.delUserValue(UserUtils.getUser().getLoginName(),UserUtils.getUser().getId()) >= 1){
                String token = UserUtils.getToken();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(token)) {
                    CacheUtils.remove(UserUtils.getUser().getLoginName());
                    UserUtils.clearCache();
                    UserUtils.getSubject().logout();
                }
                return AjaxJson.success("操作成功！");
            }else{
                log.error("用户注销失败！");
                return AjaxJson.error("用户注销失败！");
            }
        }else{
            log.error("用户未登录！");
            return AjaxJson.error("用户未登录！");
        }
    }

    /**
     * 获取用户微信id
     *
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "/getUserOpenid", method = RequestMethod.GET)
    public AjaxJson getUserOpenid() throws UnsupportedEncodingException {
        if(null != UserUtils.getUser() && StringUtils.isNotBlank(UserUtils.getUser().getLoginName())){
            return AjaxJson.success().put("wxid",UserUtils.getUser().getLoginName()).put("tell",Base64.encodeBase64String(UserUtils.getUser().getPhone().getBytes("utf-8")));
        }else{
            log.error("用户未登录！");
            return AjaxJson.error("用户未登录！");
        }
    }

    /**
     * 获取用户微信id
     *
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "/updateUserValue", method = RequestMethod.POST)
    public AjaxJson updateUserValue(String newTell,String tell,String code,String openid) {
        newTell = new String(Base64.decodeBase64(newTell));
        tell = new String(Base64.decodeBase64(tell));
        Integer result = userService.getUserPhone(newTell);
        if(result != 0){
            return AjaxJson.error("该手机号已注册!");
        }
        String cache_key = openid + "-" + newTell;
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, cache_key);
        if (null == cacheInfo) {
            return AjaxJson.error("验证失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(code)) {
                userService.updateUserValue(newTell,openid,tell);
                // 清除用户缓存
                UserUtils.clearCache(UserUtils.getUser());
                CacheUtils.remove(VERIFICATION_CODE_CACHE, cache_key);
                return AjaxJson.success("操作成功");
            }else {
                return AjaxJson.error("验证错误！");
            }
        }
    }

    /**
     * 获取用户微信id
     *
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "/checkUserTellCode", method = RequestMethod.GET)
    public AjaxJson updateUserValue(String tell,String code,String openid) throws UnsupportedEncodingException {
        tell = new String(Base64.decodeBase64(tell));
        String cache_key = openid + "-" + tell;
        Object cacheInfo = CacheUtils.get(VERIFICATION_CODE_CACHE, cache_key);
        if (null == cacheInfo) {
            return AjaxJson.error("验证失效！");
        } else {
            if (cacheInfo.toString().equalsIgnoreCase(code)) {
                CacheUtils.remove(VERIFICATION_CODE_CACHE, cache_key);
                return AjaxJson.success("操作成功");
            }else {
                return AjaxJson.error("验证错误！");
            }
        }
    }

    @RequiresPermissions("user")
    @GetMapping("getlegalUser")
    public AjaxJson getlegalUser() {
        User user = UserUtils.getUser();
        if(user != null && StringUtils.isNotBlank(user.getLoginName())){
            return AjaxJson.success().put("data",userService.checklegalUser(user.getLoginName()));
        }else{
            return AjaxJson.error("用户失效");
        }
    }

    @RequiresPermissions("user")
    @GetMapping("findUserCheck")
    public AjaxJson findUserCheck() {
        User user = UserUtils.getUser();
        if(user != null && StringUtils.isNotBlank(user.getLoginName())){
            return AjaxJson.success().put("data",userService.findUserCheck(user.getLoginName()));
        }else{
            return AjaxJson.error("用户失效");
        }
    }

    @RequiresPermissions("user")
    @GetMapping("legalList")
    public AjaxJson legalList(){
        return AjaxJson.success().put("data",userService.legalList(UserUtils.getUser().getLoginName()));
    }

    @RequiresPermissions("user")
    @GetMapping("legalByIdcard")
    public AjaxJson legalByIdcard(String idcard){
        return AjaxJson.success().put("data",userService.legalByIdcard(idcard));
    }

    @RequiresPermissions("user")
    @GetMapping("delLegal")
    public AjaxJson delLegal(String id){
        return AjaxJson.success().put("data",userService.delLegal(id));
    }

    @RequiresPermissions("user")
    @GetMapping("bindLegal")
    public AjaxJson bindLegal(String id){
        if(userService.intolegalUserAll(id) >= 1){
            return AjaxJson.success();
        }else{
            return AjaxJson.error("授权失败！");
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequiresPermissions("user")
    @GetMapping("getUserCompany")
    public AjaxJson getUserCompany() {
        System.out.println(UserUtils.getUser().getLoginName());
        return AjaxJson.success().put("user", userService.getUserCompany(UserUtils.getUser().getLoginName()));
    }


}
